<script setup>
  import {reactive, ref} from "vue"
  import { getMessageListAPI, addMessageAPI } from "./api/message";
  // 留言表单
  const messageForm = reactive({
    from: "",
    to: "",
    message: ""
  })
  // 留言列表
  const messageList = ref([])
  // 获取留言列表
  const getMessageList = async () => {
    messageList.value = await getMessageListAPI()
  } 
  // 新增留言
  const addMessage = async () => {
    // 校验内容
    if(messageForm.from === "" 
    || messageForm.to === ""
    || messageForm.message === "") {
      return window.alert("内容不可为空！")
    }
    // 新增
    const addStatus = await addMessageAPI(messageForm)
    if(addStatus) {
      // 提示
      window.alert("新增成功！")
      // 重新获取留言列表，以刷新页面
      getMessageList()
      // 清空表单
      Object.keys(messageForm).forEach(key => {
        messageForm[key] = ""
      })
    } else {
      return window.alert("新增失败，请稍后重试！")
    }
  }
  getMessageList()
    
</script>

<template>
  <div class="container">
    <div class="header">
      <h3>留言板</h3>
      <p class="tips">输入后点击提交，会将信息显示在下方空白处</p>
    </div>
    <div class="body">
      <table>
        <tr>
          <td>谁：</td>
          <td><input type="text" v-model="messageForm.from"></td>
        </tr>
        <tr>
          <td>对谁：</td>
          <td><input type="text" v-model="messageForm.to"></td>
        </tr>
        <tr>
          <td>说什么：</td>
          <td><input type="text" v-model="messageForm.message"></td>
        </tr>
        <tr>
          <td colspan="2">
            <button class="submit" @click="addMessage">提 交</button>
          </td>
        </tr>
      </table>
    </div>
    <div class="footer">
      <p v-for="item, index in messageList" :key="index">
        {{ item.from }}对{{ item.to }}说：{{ item.message }}
      </p>
    </div>

  </div>
</template>

<style scoped lang="scss">
  .container {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    .header {
      text-align: center;
      .tips {
        font-size: 14px;
        color: #bbb;
      }
    }
    .body {
      .submit {
        width: 280px;
        height: 32px;
        background-color: #f3b541;
        border: none;
        border-radius: 2px;
        color: #fff;
        font-size: 16px;
        cursor: pointer;
      }
      input {
        width: 190px;
        height: 26px;
      }
    }
    .footer {
      margin-top: 8px;
      padding: 5px 8px;
      height: 220px;
      width: 380px;
      border: 1px solid #ccc;
      border-radius: 4px;
      // 滑动条效果
      overflow: auto;
      font-size: 14px;

    }
  }
</style>